/**
 * 19. 删除链表的倒数第 N 个结点
 *
 *【中等】
 *
 * 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
 *
 * 示例 1：
 * 【https://assets.leetcode.com/uploads/2020/10/03/remove_ex1.jpg】
 * 输入：head = [1,2,3,4,5], n = 2
 * 输出：[1,2,3,5]
 *
 * 示例 2：
 * 输入：head = [1], n = 1
 * 输出：[]
 *
 * 示例 3：
 * 输入：head = [1,2], n = 1
 * 输出：[1]
 */
import { ListNode } from '../utils/list'
function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
	const dummy = new ListNode()
	dummy.next = head
	let fast = dummy
	let slow = dummy

	// 快指针闷头走 n 步
	while (n != 0) {
		fast = fast.next as ListNode
		n--
	}

	while (fast && fast.next) {
		fast = fast.next as ListNode
		slow = slow.next as ListNode
	}

	slow.next = slow.next?.next as ListNode

	return dummy.next
}
